package cs554.androidkids;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class ClickListener implements OnItemClickListener {

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		GridView gridView = (GridView) parent;
		int blank = ((ImageAdapter) gridView.getAdapter()).blankPos;
		Log.i(Utils.TAG, "blank is " + blank);

		int[] neighbors = getAdjacent(gridView, position);
		for (int i = 0; i < neighbors.length; i++) {
			Log.i(Utils.TAG, "neighbor is " + neighbors[i]);

			if (blank == neighbors[i]) {
				Log.i(Utils.TAG, "swapping " + position + " and " + blank);
				ImageAdapter adapter = (ImageAdapter) gridView.getAdapter();
				adapter.swap(position);
				adapter.notifyDataSetChanged();
				break;
			}
		}
	}

	/**
	 * Given a GridView v and one of its child at position pos, return positions
	 * of adjacent children of the child in v
	 */
	private int[] getAdjacent(GridView v, int pos) {
		assert pos >= 0 && pos < v.getNumColumns() * v.getNumColumns();
		if (isTopmost(v, pos)) {
			if (isLeftmost(v, pos))
				// upper left corner
				return new int[] { pos + 1, pos + v.getNumColumns() };
			else if (isRightmost(v, pos))
				// upper right corner
				return new int[] { pos - 1, pos + v.getNumColumns() };
			else
				// top but not corners
				return new int[] { pos - 1, pos + 1, pos + v.getNumColumns() };
		} else if (isBottom(v, pos)) {
			if (isLeftmost(v, pos))
				// bottom left corner
				return new int[] { pos - v.getNumColumns(), pos + 1 };
			else if (isRightmost(v, pos))
				// bottom right corner
				return new int[] { pos - v.getNumColumns(), pos - 1 };
			else
				// bottom but not corners
				return new int[] { pos - v.getNumColumns(), pos - 1, pos + 1 };
		} else if (isLeftmost(v, pos)) {
			// no corners anymore since both top and bottom have been
			// checked
			return new int[] { pos - v.getNumColumns(), pos + 1,
					pos + v.getNumColumns() };
		} else if (isRightmost(v, pos)) {
			// no corners anymore since both top and bottom have been
			// checked
			return new int[] { pos - v.getNumColumns(), pos - 1,
					pos + v.getNumColumns() };
		} else {
			// in the middle
			return new int[] { pos - v.getNumColumns(), pos - 1, pos + 1,
					pos + v.getNumColumns() };
		}
	}

	private boolean isTopmost(GridView v, int pos) {
		return pos >= 0 && pos < v.getNumColumns();
	}

	private boolean isBottom(GridView v, int pos) {
		return pos >= v.getNumColumns() * (v.getNumColumns() - 1)
				&& pos < v.getChildCount();
	}

	private boolean isLeftmost(GridView v, int pos) {
		return pos % v.getNumColumns() == 0;
	}

	private boolean isRightmost(GridView v, int pos) {
		return pos % v.getNumColumns() == v.getNumColumns() - 1;
	}

}
